#pragma once
#include "server.hpp"
#include <fstream>
#include <sys/stat.h>
#include <regex.h>
#include <bits/regex.h>

std::unordered_map<int, std::string> _status_msg = {
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}};

// 通用工具类------------------------------------------------------------------------------------------------------------------------------------
class Util
{
    // 分割字符串
    static size_t Split(const std::string &src, const std::string &sep, std::vector<std::string> *array)
    {
        size_t offset = 0;
        while (offset < src.size())
        {
            // 查找sep分隔符位置
            size_t pos = src.find(sep, offset);
            // 没有找到
            if (pos == std::string::npos)
            {
                std::string tmp = src.substr(offset);
                array->push_back(tmp);
                break;
            }
            // 处理连续出现的分隔符情况--否则往下运行的话，array会插入空字符串
            if (pos == offset)
            {
                offset = pos + sep.size();
                continue;
            }
            // 找到了
            std::string tmp = src.substr(offset, pos - offset);
            array->push_back(tmp);
            offset = pos + sep.size();
        }
        // 返回字串数量
        return array->size();
    }
    // 读取文件
    static bool ReadFile(const std::string &filename, std::string *buf)
    {
        // 以二进制流的方式打开
        std::ifstream ifs(filename, std::ios::binary);
        if (ifs.is_open() == false)
        {
            ERR_LOG("OPEN %s FILE FAIL", filename.c_str());
            return false;
        }
        size_t file_size = 0;
        // 将文件指针跳转到文件末尾
        ifs.seekg(0, ifs.end);
        // 读取文件指针相对于文件开头的偏移量 -- 计算出文件大小
        file_size = ifs.tellg();
        ifs.read(&(*buf)[0], file_size);
        if (ifs.good())
        {
            ERR_LOG("READ %s FILE FAIL", filename.c_str());
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
    }
    // 写入文件
    static bool WriteFile(const std::string &filename, const std::string &buf)
    {
        // 以二进制流方式写入并且清空写入
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if (ofs.is_open())
        {
            ERR_LOG("OPEN %s FILE FAIL", filename.c_str());
            return false;
        }
        // 写入数据
        ofs.write(buf.c_str(), buf.size());
        if (ofs.good())
        {
            ERR_LOG("WRITE %s FILE FAIL", filename.c_str());
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }
    // 响应状态码的描述信息获取
    static std::string StatusDesc(int status)
    {
        auto it = _status_msg.find(status);
        if (it == _status_msg.end())
        {
            return "Unknow";
        }
        return it->second;
    }
    // 根据文件后缀名获取mime
    static std::string ExtMine(const std::string &filename)
    {
        size_t pos = filename.rfind('.');
        if (pos == std::string::npos)
        {
            return "application/octet-stream";
        }

        // 获取文件后缀
        std::string tmp = filename.substr(pos);
        auto it = _mime_msg.find(tmp);
        if (it == _mime_msg.end())
        {
            return "application/octet-stream";
        }
        return it->second;
    }
    // 判断一个文件是不是目录
    static bool IsDirectory(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;

        return S_ISDIR(st.st_mode);
    }
    // 判断一个文件是否是普通文件
    static bool IsRegular(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;
        return S_ISREG(st.st_mode);
    }
    // 判断一个路径是否有效
    static bool ValidPath(const std::string &path)
    {
        // 切分路径
        std::vector<std::string> subdir;
        Split(path, "/", &subdir);

        // 判断
        int level = 0; // 定义层数
        for (auto &dir : subdir)
        {
            if (dir == "..")
                level--;
            else
                level++;
            if (level < 0)
                return false;
        }
        return true;
    }

    // URL编码
    static std::string UrlEncode(const std::string &url, bool convert_space_to_plus)
    {
        std::string ret;
        for (auto ch : url)
        {
            // 不需要编码的字符
            if (ch == '.' || ch == '-' || ch == '_' || ch == '~' || isalnum(ch))
            {
                ret += ch;
                continue;
            }
            if (convert_space_to_plus == true && ch == ' ')
            {
                ret += '+';
                continue;
            }
            // 字符---转换为16进制数字的字符串
            char tmp[4] = {0};
            snprintf(tmp, 4, "%%%02X", ch);
            ret += tmp;
        }
        return ret;
    }
    // 字符和数字的转换
    static int HEXTOI(char c)
    {
        if (c >= '0' && c <= '9')
            return c - '0';
        else if (c >= 'a' && c <= 'z')
            return c - 'a' + 10;
        else if (c >= 'A' && c <= 'Z')
            return c = 'A' + 10;
        else
            return -1;
    }
    // URL解码
    static std::string UrlDecode(const std::string &url, bool convert_plus_to_space)
    {
        std::string ret;
        for (int i = 0; i < url.size(); i++)
        {
            // 空格和+的转换
            if (convert_plus_to_space == true && url[i] == '+')
            {
                ret += " ";
                continue;
            }
            // 16进制数字的字符串--每个字符转化为10进制字符--整体转化为10进制字符
            if (url[i] == '%' && (i + 2) < url.size())
            {
                int v1 = HEXTOI(url[i + 1]);
                int v2 = HEXTOI(url[i + 2]);
                char v = v1 * 16 + v2;
                ret += v;
                i += 2;
                continue;
            }
            ret += url[i];
        }
        return ret;
    }
};

// 请求报文保存模块------------------------------------------------------------------------------------------------------------------------------------
class HttpRequest
{
public:
    std::string _method;  // 请求方法
    std::string _path;    // 请求路径
    std::string _version; // 协议版本
    std::string _body;    // 请求正文
    std::smatch _matches; // 资源路径的正则提取数据

    std::unordered_map<std::string, std::string> _headers; // 头部字段
    std::unordered_map<std::string, std::string> _params;  // 查询字符串

public:
    HttpRequest() : _version("HTTP/1.1") {}
    // 重新设置
    void Reset()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch matches;
        matches.swap(_matches);
        _headers.clear();
        _params.clear();
    }

    // 插入头部字段
    void SetHeader(const std::string &key, const std::string &val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    // 判断是否存在指定的头部字段
    bool HasHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return false;
        return true;
    }
    // 获取指定的头部字段的值
    std::string GetHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return "";
        return it->second;
    }

    // 插入查询字符串
    void SetParam(const std::string &key, const std::string &val)
    {
        _params.insert(std::make_pair(key, val));
    }
    // 判断是否有指定的查询字符串
    bool HasParam(const std::string &key) const
    {
        auto it = _params.find(key);
        if (it == _params.end())
            return false;
        return true;
    }
    // 获取指定的查询字符串
    std::string GetParam(const std::string &key) const
    {
        auto it = _params.find(key);
        if (it == _params.end())
            return "";
        return it->second;
    }

    // 获取正文长度
    size_t ContentLength() const
    {
        bool ret = HasHeader("Content-Length");
        if (ret == false)
            return 0;
        std::string length = GetHeader("Content-Length");
        return std::stoi(length);
    }

    // 判断是否是短连接
    bool Close() const
    {
        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};

// 响应报文保存模块------------------------------------------------------------------------------------------------------------------------------------
class HttpResponse
{
public:
    int _status;               // 响应状态码
    bool _redirect_flag;       // 是否进行重定向
    std::string _body;         // 响应正文
    std::string _redirect_url; // 重定向url

    std::unordered_map<std::string, std::string> _headers; // 头部字段

public:
    HttpResponse() : _status(200), _redirect_flag(false) {}
    HttpResponse(int status) : _status(status), _redirect_flag(false) {}

    // 重新设置
    void ReSet()
    {
        _status = 200;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }

    // 插入头部字段
    void SetHeader(const std::string &key, const std::string &val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    // 判断是否存在指定的头部字段
    bool HasHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return false;
        return true;
    }
    // 获取指定的头部字段的值
    std::string GetHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return "";
        return it->second;
    }

    // 设置响应正文
    void SetContent(const std::string &body, const std::string &type = "text/html")
    {
        _body = body;
        SetHeader("Content-Type", type);
    }
    // 设置重定向
    void SetRedirect(const std::string &url, int status = 302)
    {
        _status = status;
        _redirect_flag = true;
        _redirect_url = url;
    }

    // 判断是否是短连接
    bool Close() const
    {
        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};

// 上下文模块------------------------------------------------------------------------------------------------------------------------------------

enum TcpRecvStauts
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
};
static const size_t MAX_LINE = 8192;

class Context
{
private:
    HttpRequest _req;           // 请求报文
    int _resp_status;           // 响应状态码
    TcpRecvStauts _recv_status; // 一个完整的报文处理和解析的阶段

private:
    //处理请求行
    bool ParseHttpLine(const std::string &line)
    {
        std::smatch matches;
        std::regex e()
    }
    bool RecvHttpLine(Buffer *buf)
    {
        std::string line = buf->GetLine();
        //没有一行数据
        if(line.size() == 0)
        {
            //如果说buf里有很大的数据，但是还是没有换行字符，那么就会有问题
            if(buf->ReadAbleSize() > MAX_LINE)
            {
                _resp_status = 414;
                _recv_status = RECV_HTTP_ERROR;
                return false;
            }
            return true;
        }        
        //有一行数据，但是太长了
        if(buf->ReadAbleSize() > MAX_LINE)
        {
            _resp_status = 414;
            _recv_status = RECV_HTTP_ERROR;
            return false;
        }
        //解析首行数据
        bool ret = ParseHttpLine(line);
        if(ret == false)
            return false;
        
        _recv_status = RECV_HTTP_HEAD;
        return true;
    }

    bool RecvHttpHead(Buffer *buf);
    {

    }
    bool RecvHttpBody(Buffer *buf)
    {

    }

public:
    Context() : _resp_status(200), _recv_status(RECV_HTTP_LINE) {}
    // 清空上下文
    void ReSet()
    {
        _req.Reset();
        _resp_status = 200;
        _recv_status = RECV_HTTP_LINE;
    }
    // 获取请求报文
    HttpRequest &GetHttpRequest() { return _req; }
    // 获取响应状态码
    int GetResponseStatus() { return _resp_status; }
    // 获取处理的阶段
    TcpRecvStauts GetRecvStatus() { return _recv_status; }

    //处理请求
    void HandleRequest(Buffer *buffer)
    {
        switch(_recv_status)
        {
            case RECV_HTTP_LINE: RecvHttpLine(buf);
            case RECV_HTTP_HEAD: RecvHttpHead(buf);
            case RECV_HTTP_BODY: RecvHttpBody(buf);
        }
    }
};